package com.rongxun.common.base.mvp;


import com.rongxun.common.R;
import com.yanzhenjie.permission.AndPermission;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 创建者     forza
 * 创建时间   2019/11/29 18:09
 * 描述
 */
public abstract class BasePresenter<V extends IBase.IView, M extends IBase.IModel> implements IBase.IPresenter {

    protected CompositeDisposable mCompositeDisposable;
    protected V                   mView;
    private   M                   mModel;


    public BasePresenter(@NonNull V pUi) {
        mView = pUi;
    }

    public BasePresenter(@NonNull V pUi, @NonNull M pModel) {
        mView = pUi;
        mModel = pModel;
    }

    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    public void checkPermissions(final FragmentActivity activity, final String... permissions) {

        AndPermission.with(activity).runtime().permission(permissions)
                .onGranted(data -> getView().checkPermissionsSuccessful(permissions))
                .onDenied(data -> getView().showError(activity.getString(R.string.no_permission), "0000"))
                .start();
    }


    protected void removeSubscribe(Disposable subscription) {
        if (subscription == null) {
            return;
        }
        if (mCompositeDisposable != null) {
            mCompositeDisposable.remove(subscription);
        }
    }

    protected <T extends Disposable> T addSubscribe(T subscription) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);

        return subscription;
    }

    public final M getModel() {
        return mModel;
    }

    public final V getView() {
        return mView;
    }

    @Override
    public void release() {
        innerRelease();
        unSubscribe();
        if (mModel != null) {
            mModel.release();
        }
        if (mView != null) {
            mView.release();
            mView = null;
        }
        if (mModel != null) {
            mModel.release();
            mModel = null;
        }

    }

    /**
     * 其他资源的释放
     */
    protected void innerRelease() {

    }

}
